//
//  ErViewController.m
//  二维码
//
//  Created by apple on 2017/8/23.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "ErViewController.h"
#import <AVFoundation/AVFoundation.h>
//#import "YYResultViewController.h"
#import "APPUtilsMacro.h"
#import <Masonry.h>

#define TOP 200 * Scale_Ratio
#define LEFT 50 * Scale_Ratio
#define scan_Width (Screen_Width - LEFT * 2)
#define kScanRect CGRectMake(LEFT, TOP, scan_Width, scan_Width)
@interface ErViewController ()<AVCaptureMetadataOutputObjectsDelegate>

{
    int num;
    BOOL upOrdown;
    NSTimer * timer;
    CAShapeLayer *cropLayer;
    UIImageView *_rectImageView;
    CGRect _tempRect;
}

@property (strong,nonatomic)AVCaptureDevice * device;
@property (strong,nonatomic)AVCaptureDeviceInput * input;
@property (strong,nonatomic)AVCaptureMetadataOutput * output;
@property (strong,nonatomic)AVCaptureSession * session;
@property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview;



@property (nonatomic, strong) UIImageView * line;

@property (nonatomic, strong) UIActivityIndicatorView *activityView;

@end

@implementation ErViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    self.view.backgroundColor = [UIColor lightGrayColor];
    
    self.activityView.center = self.view.center;
    [self.activityView startAnimating];
    
    //    [self configView];
    
    
    
    __weak ErViewController *weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [weakSelf.activityView stopAnimating];
        
        [weakSelf configView];
        [weakSelf setCropRect:kScanRect];
        [weakSelf setupCamera];
    });
    

}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self removeTimer];
}

#pragma mark - - - 移除定时器
- (void)removeTimer {
    [timer invalidate];
    timer = nil;
    [cropLayer removeFromSuperlayer];
    self.line = nil;
}




-(void)configView{
    
    UIImageView * imageView = [[UIImageView alloc]init];
    imageView.image = [UIImage imageNamed:@"pick_bg"];
    [self.view addSubview:imageView];
    imageView.layer.borderWidth = 0.5;
    imageView.layer.borderColor = [UIColor whiteColor].CGColor;
    _rectImageView = imageView;
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(50 * Scale_Ratio);
        make.right.equalTo(self.view.mas_right).offset(-50 * Scale_Ratio);
        make.top.equalTo(self.view.mas_top).offset(200 * Scale_Ratio);
        make.width.equalTo(imageView.mas_height).multipliedBy(1);
    }];
    
    
    
    
    
    UILabel *label = [[UILabel alloc] init];
    [self.view addSubview:label];
    label.textColor = [[UIColor whiteColor] colorWithAlphaComponent:1];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"将二维码/条码放入框内, 即可自动扫描";
    label.font = [UIFont boldSystemFontOfSize:FontSize11];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(imageView.mas_left);
        make.right.equalTo(imageView.mas_right);
        make.top.equalTo(imageView.mas_bottom).offset(5);
        make.height.mas_equalTo(30);
    }];
    
    
    
    UIButton *light_button = [[UIButton alloc] init];
    [self.view addSubview:light_button];
    [light_button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(label.mas_left).offset(20 * Scale_Ratio);
        make.right.equalTo(label.mas_right).offset(-20 * Scale_Ratio);
        make.top.equalTo(label.mas_bottom).offset(20 * Scale_Ratio);
        make.height.mas_equalTo(20 * Scale_Ratio);
    }];
    [light_button setTitle:@"打开照明灯" forState:UIControlStateNormal];
    [light_button setTitle:@"关闭照明灯" forState:UIControlStateSelected];
    [light_button setTitleColor:label.textColor forState:(UIControlStateNormal)];
    light_button.titleLabel.font = [UIFont systemFontOfSize:FontSize13];
    
    [light_button addTarget:self action:@selector(light_buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    upOrdown = NO;
    num =0;
    _line = [[UIImageView alloc] initWithFrame:CGRectMake(LEFT, TOP+10, scan_Width, 2)];
    _line.image = [UIImage imageNamed:@"line.png"];
    [self.view addSubview:_line];
    
    timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
    
}

#pragma mark -- 私有点击方法
-(void)animation1
{
    if (upOrdown == NO) {
        num ++;
        _line.frame = CGRectMake(LEFT, TOP+10+2*num, scan_Width, 2);
        if (2*num >= (scan_Width - 20)) {
            upOrdown = YES;
        }
    }
    else {
        num --;
        _line.frame = CGRectMake(LEFT, TOP+10+2*num, scan_Width, 2);
        if (num == 0) {
            upOrdown = NO;
        }
    }
    
}

- (void)setCropRect:(CGRect)cropRect{
    
    
    cropLayer = [[CAShapeLayer alloc] init];
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, nil, cropRect);
    CGPathAddRect(path, nil, self.view.bounds);
    
    [cropLayer setFillRule:kCAFillRuleEvenOdd];
    [cropLayer setPath:path];
    [cropLayer setFillColor:[UIColor blackColor].CGColor];
    [cropLayer setOpacity:0.6];
    [cropLayer setNeedsDisplay];
    
    [self.view.layer addSublayer:cropLayer];
}

- (void)setupCamera
{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device==nil) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"设备没有摄像头" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    // Device
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    // Output
    _output = [[AVCaptureMetadataOutput alloc]init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    //设置扫描区域
    CGFloat top = TOP/Screen_Height;
    CGFloat left = LEFT/Screen_Width;
    CGFloat width = 220/Screen_Width;
    CGFloat height = 220/Screen_Height;
    ///top 与 left 互换  width 与 height 互换
    [_output setRectOfInterest:CGRectMake(top,left, height, width)];
    
    
    // Session
    _session = [[AVCaptureSession alloc]init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    if ([_session canAddInput:self.input])
    {
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output])
    {
        [_session addOutput:self.output];
    }
    
    // 条码类型 AVMetadataObjectTypeQRCode   @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code]
    [_output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code]];
    
    // Preview
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:_session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _preview.frame =self.view.layer.bounds;
    [self.view.layer insertSublayer:_preview atIndex:0];
    
    // Start
    [_session startRunning];
}


//照明灯 点击事件
- (void)light_buttonAction:(UIButton *)button {
    if (button.selected == NO) { // 点击打开照明灯
        [self turnOnLight:YES];
        button.selected = YES;
    } else { // 点击关闭照明灯
        [self turnOnLight:NO];
        button.selected = NO;
    }
}
- (void)turnOnLight:(BOOL)on {
    self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([_device hasTorch]) {
        [_device lockForConfiguration:nil];
        if (on) {
            [_device setTorchMode:AVCaptureTorchModeOn];
        } else {
            [_device setTorchMode: AVCaptureTorchModeOff];
        }
        [_device unlockForConfiguration];
    }
}






#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    NSString *stringValue;
    
    if ([metadataObjects count] >0)
    {
        // 0、扫描成功之后的提示音
        [self SG_playSoundEffect:@"sound.caf"];
        
        //停止扫描
        [_session stopRunning];
        [timer setFireDate:[NSDate distantFuture]];
        
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        //        NSLog(@"扫描结果：%@",stringValue);
        
        //        NSArray *arry = metadataObject.corners;
        //        for (id temp in arry) {
        //            NSLog(@"%@",temp);
        //        }
        
        
        //        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"扫描结果" message:stringValue preferredStyle:UIAlertControllerStyleAlert];
        //        [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //            if (_session != nil && timer != nil) {
        //                [_session startRunning];
        //                [timer setFireDate:[NSDate date]];
        //            }
        //
        //        }]];
        //        [self presentViewController:alert animated:YES completion:nil];
        
        
        if(!stringValue.length){
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"扫描结果" message:@"扫描错误" preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                if (_session != nil && timer != nil) {
                    [_session startRunning];
                    [timer setFireDate:[NSDate date]];
                }
            }]];
            [self presentViewController:alert animated:YES completion:nil];
        }
        
//        YYResultViewController *resultVc = [[YYResultViewController alloc] init];
//        resultVc.offSetX = self.offSetX;
//        resultVc.manageType = self.manageType;
//        resultVc.orderId = stringValue;
//        resultVc.pushSYSTag = SYSTag;
//        [self.navigationController pushViewController:resultVc animated:YES];
        
    } else {
        NSLog(@"无扫描信息");
        return;
    }
    
}


-(UIActivityIndicatorView *)activityView
{
    if(!_activityView)
    {
        _activityView = [[UIActivityIndicatorView alloc] init];
        [self.view addSubview:_activityView];
    }
    return _activityView;
}


/** 播放音效文件 */
- (void)SG_playSoundEffect:(NSString *)name {
    // 获取音效
    NSString *audioFile = [[NSBundle mainBundle] pathForResource:name ofType:nil];
    NSURL *fileUrl = [NSURL fileURLWithPath:audioFile];
    
    // 1、获得系统声音ID
    SystemSoundID soundID = 0;
    
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileUrl), &soundID);
    
    AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, soundCompleteCallback, NULL);
    
    // 2、播放音频
    AudioServicesPlaySystemSound(soundID); // 播放音效
}
/** 播放完成回调函数 */
void soundCompleteCallback(SystemSoundID soundID, void *clientData){
    //SGQRCodeLog(@"播放完成...");
}


@end
